package com.eostoken.eos_wallet.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.FrameLayout;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.Fragment;

import com.blankj.utilcode.constant.PermissionConstants;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.BusUtils;
import com.blankj.utilcode.util.ColorUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.UtilsTransActivity;
import com.eostoken.eos_wallet.MainActivity;
import com.eostoken.eos_wallet.R;
import com.eostoken.eos_wallet.base.BaseFragment;
import com.eostoken.eos_wallet.bean.AccountInfo;
import com.eostoken.eos_wallet.bean.AccountNames;
import com.eostoken.eos_wallet.bean.EOSPrice;
import com.eostoken.eos_wallet.bus.ToWallet;
import com.eostoken.eos_wallet.db.MgpWallet;
import com.eostoken.eos_wallet.eosnet.common.Params;
import com.eostoken.eos_wallet.helper.DialogHelper;
import com.eostoken.eos_wallet.mvp.callback.CommonCallback;
import com.eostoken.eos_wallet.mvp.mode.HomeModel;
import com.eostoken.eos_wallet.mvp.presenter.HomePresenterImpl;
import com.eostoken.eos_wallet.mvp.view.HomeView;
import com.eostoken.eos_wallet.ui.activity.AssistCreateActivity;
import com.eostoken.eos_wallet.ui.activity.BaseWalletActivity;
import com.eostoken.eos_wallet.ui.activity.MoneyReceivingQRCodeActivity;
import com.eostoken.eos_wallet.ui.activity.MyWalletInfoActivity;
import com.eostoken.eos_wallet.ui.activity.QrcodeScanActivity;
import com.eostoken.eos_wallet.ui.activity.ResourceAdministrationActivity;
import com.eostoken.eos_wallet.ui.activity.VoteActivity;
import com.eostoken.eos_wallet.ui.activity.WalletFunctionActivity;
import com.eostoken.eos_wallet.ui.activity.WalletListActivity;
import com.eostoken.eos_wallet.utils.ClipboardUtils;
import com.eostoken.eos_wallet.utils.Constants;
import com.eostoken.eos_wallet.utils.WalletUtils;
import com.qmuiteam.qmui.widget.QMUIRadiusImageView;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.qmuiteam.qmui.widget.pullRefreshLayout.QMUIPullRefreshLayout;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;

import java.math.BigDecimal;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import party.loveit.eosforandroidlibrary.Ecc;

import static com.eostoken.eos_wallet.utils.Constants.ACCOUNTS;
import static com.eostoken.eos_wallet.utils.Constants.ACCOUNT_INFO;
import static com.eostoken.eos_wallet.utils.Constants.ACTIVATE_ACCOUNT;
import static com.eostoken.eos_wallet.utils.Constants.BUS_DELETE_WALLET;
import static com.eostoken.eos_wallet.utils.Constants.BUS_TO_WALLET;
import static com.eostoken.eos_wallet.utils.Constants.EXTRA_CREATE_ACCOUNT_DATA;
import static com.eostoken.eos_wallet.utils.Constants.EXTRA_INTERSECTION;
import static com.eostoken.eos_wallet.utils.Constants.EXTRA_TRANSACTION_LIST;
import static com.eostoken.eos_wallet.utils.Constants.EXTRA_WALLET;
import static com.eostoken.eos_wallet.utils.Constants.IMPORT_WALLET;
import static com.eostoken.eos_wallet.utils.Constants.INTENT_EXTRA_KEY_QR_SCAN;
import static com.eostoken.eos_wallet.utils.Constants.PRICE;
import static com.eostoken.eos_wallet.utils.Constants.PROCEEDS;
import static com.eostoken.eos_wallet.utils.Constants.REQUEST_CUT_WALLET;
import static com.eostoken.eos_wallet.utils.Constants.RESOURCE_ADMINISTRATION;
import static com.eostoken.eos_wallet.utils.Constants.TO_CREATE_WALLET;
import static com.eostoken.eos_wallet.utils.Constants.TO_IMPORT_WALLET_PRIVATEKEY;
import static com.eostoken.eos_wallet.utils.Constants.TO_IMPORT_WALLET_MNEMONIC;
import static com.eostoken.eos_wallet.utils.Constants.TO_TRANSFER_WALLET;
import static com.eostoken.eos_wallet.utils.Constants.TRANSFER;
import static com.eostoken.eos_wallet.utils.Constants.WALLET_INFO;
import static com.eostoken.eos_wallet.utils.Constants.WALLET_MANAGEMENT;

public class HomeFragment extends BaseFragment<HomeModel, HomeView, HomePresenterImpl> implements HomeView, QMUIPullRefreshLayout.OnPullListener {

    @BindView(R.id.topBar)
    QMUITopBarLayout topbar;
    @BindView(R.id.moreIv)
    AppCompatImageView moreIv;
    @BindView(R.id.walletNameTv)
    AppCompatTextView walletNameTv;
    @BindView(R.id.walletTotalBalanceTv)
    AppCompatTextView walletTotalBalanceTv;
    @BindView(R.id.walletCardView)
    CardView walletCardView;
    @BindView(R.id.NodeVoteBtn)
    QMUIRoundButton NodeVoteBtn;
    @BindView(R.id.ResManageBtn)
    QMUIRoundButton ResManageBtn;
    @BindView(R.id.walletIconTv)
    QMUIRadiusImageView walletIconTv;
    @BindView(R.id.walletTypeTv)
    AppCompatTextView walletTypeTv;
    @BindView(R.id.walletCoinTv)
    AppCompatTextView walletCoinTv;
    @BindView(R.id.EOSBalanceTv)
    AppCompatTextView EOSBalanceTv;
    @BindView(R.id.eosPriceTv)
    AppCompatTextView eosPriceTv;
    @BindView(R.id.toActivateTv)
    AppCompatTextView toActivateTv;
    @BindView(R.id.walletInfoLayout)
    FrameLayout walletInfoLayout;
    @BindView(R.id.pull_to_refresh)
    QMUIPullRefreshLayout pullRefreshLayout;
    @BindView(R.id.walletMainNameTv)
    AppCompatTextView walletMainNameTv;


    private boolean isBalance = false;
    private boolean isPrice = false;
    private BigDecimal bdPrice = null;
    private BigDecimal bdBalance = null;
    private BigDecimal bdTotalAmount = null;
    private String currentAccountName = "";
    private String balance = "0";
    private String price = "0";
    private String privatekey;
    private String publicKey;
    private AccountInfo accountInfo;
    public static MgpWallet wallet;
    private List<MgpWallet> walletList;
    private boolean isCutWallet = false;
    private String accountInfoJSON;
    private static MainActivity mMainActivity;
    private String walletName;

//    private static class LazyHolder {
//        private static final HomeFragment INSTANCE = new HomeFragment();
//    }
//
//    public static final HomeFragment getInstance(MainActivity mainActivity) {
//        mMainActivity = mainActivity;
//        return LazyHolder.INSTANCE;
//    }

    @Override
    protected int getContentLayout() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initData() {
        if (!isCutWallet) {
            currentAccountName = WalletUtils.getCurrentAccountName();
            privatekey = WalletUtils.getCurrentPrivatekey();
            publicKey = Ecc.privateToPublic(privatekey);
            LogUtils.dTag(Constants.TAG_MGP, "currentAccountName = " + currentAccountName);
            WalletUtils.queryWallet(getActivity(), currentAccountName, new CommonCallback() {
                @Override
                public void onSuccess(Object data, String successMsg, int responseSuccessCode) {
                    walletList = (List<MgpWallet>) data;
                    wallet = walletList.get(0);
                    privatekey = wallet.getPrivateKey();
                    publicKey = wallet.getPublicKey();
                    if (ObjectUtils.isEmpty(publicKey)) {
                        publicKey = Ecc.privateToPublic(privatekey);
                    }
                    updateWalletNameView();
                }

                @Override
                public void onFailure(String msg, int responseFailCode) {
                }
            });
            presenter.requestDIGICCYPrice(Constants.PRICE_MGP);
        }
        presenter.requestKeyAccounts(Params.getKeyAccountsPamars(publicKey));
        presenter.requestAccountInfo(Params.getAccountPamars(currentAccountName));
        walletNameTv.setText(currentAccountName);
        isCutWallet = false;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            isDataInitiated = false;
            updateWalletNameView();
        }
    }

    @Override
    protected void initView(View contentView) {
        pullRefreshLayout.setOnPullListener(this);
        BarUtils.setStatusBarColor(getActivity(), ColorUtils.getColor(R.color.app_color_blue));
        BarUtils.setStatusBarLightMode(getActivity(), false);
        topbar.setTitle(StringUtils.getString(R.string.str_mgp_wallet));
        topbar.addLeftImageButton(R.mipmap.menu_icon, R.id.topbar_left_change_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), WalletListActivity.class);

                startActivityForResult(intent, REQUEST_CUT_WALLET);
            }
        });
        topbar.addRightImageButton(R.mipmap.qrcode_icon_2, R.id.topbar_right_change_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startQrCode();
            }
        });
    }

    /**
     * 开始扫码
     */
    public void startQrCode() {
        PermissionUtils.permission(PermissionConstants.CAMERA, PermissionConstants.STORAGE)
                .rationale(new PermissionUtils.OnRationaleListener() {
                    @Override
                    public void rationale(UtilsTransActivity activity, ShouldRequest shouldRequest) {
                        DialogHelper.showRationaleDialog(getActivity(), shouldRequest);
                    }
                })
                .callback(new PermissionUtils.FullCallback() {
                    @Override
                    public void onGranted(List<String> permissionsGranted) {
                        Intent intent = new Intent(getActivity(), QrcodeScanActivity.class);
                        startActivityForResult(intent, Constants.REQUEST_SCAN_CODE);
                    }

                    @Override
                    public void onDenied(List<String> permissionsDeniedForever, List<String> permissionsDenied) {

                    }
                }).request();
    }

    @OnClick({R.id.toActivateTv, R.id.NodeVoteBtn, R.id.ResManageBtn, R.id.walletNameLayout, R.id.walletInfoLayout, R.id.moreIv})
    public void onViewClicked(View view) {
        int type = -1;
        Fragment fragment = null;
        Intent intent;
        Bundle bundle;
        String destTag = "";
        switch (view.getId()) {
            case R.id.NodeVoteBtn:
                ActivityUtils.startActivity(VoteActivity.class);
                break;
            case R.id.ResManageBtn:
                type = RESOURCE_ADMINISTRATION;
                intent = new Intent(getActivity(), ResourceAdministrationActivity.class);
                ActivityUtils.startActivity(intent);
                break;
            case R.id.walletNameLayout:
                type = PROCEEDS;
                intent = new Intent(getActivity(), MoneyReceivingQRCodeActivity.class);
                ActivityUtils.startActivity(intent);
                break;
            case R.id.moreIv:
                type = WALLET_MANAGEMENT;
                intent = new Intent(getActivity(), MyWalletInfoActivity.class);
                bundle = new Bundle();
                bundle.putParcelable(EXTRA_WALLET, wallet);
                intent.putExtras(bundle);
                ActivityUtils.startActivity(intent);
                break;
            case R.id.walletInfoLayout:
                type = WALLET_INFO;
                intent = new Intent(getActivity(), WalletFunctionActivity.class);
                bundle = new Bundle();
                bundle.putBoolean(EXTRA_TRANSACTION_LIST, false);
                intent.putExtras(bundle);
                ActivityUtils.startActivity(intent);
                break;
            case R.id.toActivateTv:
                type = ACTIVATE_ACCOUNT;
                intent = new Intent(getActivity(), BaseWalletActivity.class);
                intent.putExtra(EXTRA_INTERSECTION, type);
                intent.putExtra(EXTRA_WALLET, wallet);
                ActivityUtils.startActivity(intent);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        LogUtils.dTag("onScanQRCodeSuccess==", "result = " + resultCode);
        Intent intent = null;
        switch (requestCode) {
            case Constants.REQUEST_SCAN_CODE:

                if (!ObjectUtils.isEmpty(data)) {
                    Bundle bundle = data.getExtras();
                    String scanResult = bundle.getString(INTENT_EXTRA_KEY_QR_SCAN);
                    if (!ObjectUtils.isEmpty(scanResult)) {
                        if (scanResult.contains("\"type\":\"" + TO_CREATE_WALLET + "\"") || scanResult.contains("\"type\":" + TO_CREATE_WALLET)) {
                            intent = new Intent(getActivity(), AssistCreateActivity.class);
                            bundle = new Bundle();
                            bundle.putString(EXTRA_CREATE_ACCOUNT_DATA, scanResult);
                            intent.putExtras(bundle);
                            ActivityUtils.startActivity(intent);
//                        FragmentUtils.replace(getFragmentManager(), fragment, R.id.eostoken_main, "AssistCreateFragment", true);
                        } else if (scanResult.contains("\"type\":\"" + TO_TRANSFER_WALLET + "\"") || scanResult.contains("\"type\":" + TO_TRANSFER_WALLET)) {
                            intent = new Intent(getActivity(), BaseWalletActivity.class);
                            intent.putExtra(EXTRA_INTERSECTION, TRANSFER);
                            intent.putExtra(INTENT_EXTRA_KEY_QR_SCAN, scanResult);
                            ActivityUtils.startActivity(intent);
                        } else if (scanResult.contains("\"type\":\"" + TO_IMPORT_WALLET_PRIVATEKEY + "\"") || scanResult.contains("\"type\":" + TO_IMPORT_WALLET_PRIVATEKEY) ||
                                scanResult.contains("\"type\":\"" + TO_IMPORT_WALLET_MNEMONIC + "\"") || scanResult.contains("\"type\":" + TO_IMPORT_WALLET_MNEMONIC)) {
                            intent = new Intent(getActivity(), BaseWalletActivity.class);
                            intent.putExtra(EXTRA_INTERSECTION, IMPORT_WALLET);
                            intent.putExtra(INTENT_EXTRA_KEY_QR_SCAN, scanResult);
                            ActivityUtils.startActivity(intent);
                        } else {
                            DialogHelper.showLongMessageDialog(getActivity(), getString(R.string.str_prompt_message), scanResult, getString(android.R.string.cancel), getString(R.string.str_copy), new QMUIDialogAction.ActionListener() {
                                @Override
                                public void onClick(QMUIDialog dialog, int index) {
                                    dialog.dismiss();
                                }
                            }, new QMUIDialogAction.ActionListener() {
                                @Override
                                public void onClick(QMUIDialog dialog, int index) {
                                    ClipboardUtils.copyText(scanResult);
                                    ToastUtils.showShort(StringUtils.getString(R.string.str_copy_success));
                                    dialog.dismiss();
                                }
                            }).show();
                        }
                    }
                }
                break;
            case REQUEST_CUT_WALLET:

                break;
            default:
        }
    }

    @Override
    public HomeModel createModel() {
        return new HomeModel();
    }

    @Override
    public HomeView createView() {
        return this;
    }

    @Override
    public HomePresenterImpl createPresenter() {
        return new HomePresenterImpl(getActivity());
    }

    @Override
    public void finishRefresh() {

    }

    @Override
    public void updateView(Object data, int responseSuccessCode) {
        pullRefreshLayout.finishRefresh();
        switch (responseSuccessCode) {
            case PRICE:
                isPrice = true;
                EOSPrice eosPrice = (EOSPrice) data;
                EOSPrice.DataBean dataBean = eosPrice.getData();
                bdPrice = dataBean.getPrice();
                String price = bdPrice.stripTrailingZeros().toPlainString();
                if (ObjectUtils.isEmpty(price)) {
                    price = "0";
                }
                eosPriceTv.setText(String.format(StringUtils.getString(R.string.str_balance_unit_1), price));//$2.05516/EOS
                break;
            case ACCOUNT_INFO:
                isBalance = true;
                accountInfo = (AccountInfo) data;
                accountInfoJSON = GsonUtils.toJson(accountInfo);
                balance = accountInfo.getCore_liquid_balance();//5.3158 EOS
                if (!ObjectUtils.isEmpty(balance)) {
                    String[] arrB = balance.split(" ");
                    balance = arrB[0];
                } else {
                    balance = "0.0000";
                }

                EOSBalanceTv.setText(String.format(StringUtils.getString(R.string.str_balance_unit_blank), balance));

                bdBalance = new BigDecimal(balance);
                break;
            case ACCOUNTS:
                boolean isActivate = true;
                AccountNames accountNames = (AccountNames) data;
                List<String> accountNameList = accountNames.getAccount_names();
                if (accountNames == null) {
                    isActivate = false;
                } else {
                    if (GsonUtils.toJson(accountNames).contains(currentAccountName)) {
                        isActivate = true;
                    } else {
                        isActivate = false;
                    }
                }
                toActivateTv.setVisibility(isActivate ? View.GONE : View.VISIBLE);
                walletNameTv.setText(currentAccountName
                        + (isActivate ? "" : "(" + getString(R.string.str_inactive) + ")"));
                break;
        }

        if (isPrice && isBalance) {
            if (bdBalance != null && bdPrice != null) {
                bdTotalAmount = bdBalance.multiply(bdPrice);
                String total = bdTotalAmount.stripTrailingZeros().toPlainString();
                walletTotalBalanceTv.setText("$" + total);
            }
        }
    }

    @Override
    public void onFailure(Object data, int responseFailCode) {
        pullRefreshLayout.finishRefresh();
        switch (responseFailCode) {
            case PRICE:
                isPrice = true;
                price = "0";
                bdPrice = new BigDecimal(price);
                eosPriceTv.setText(String.format(StringUtils.getString(R.string.str_balance_unit_1), "0"));//$2.05516/EOS
                break;
            case ACCOUNT_INFO:
                isBalance = true;
                balance = "0";
                bdBalance = new BigDecimal(balance);
                EOSBalanceTv.setText(String.format(StringUtils.getString(R.string.str_balance_unit_blank), balance));
                break;
            case ACCOUNTS:
                boolean isActivate = false;
                toActivateTv.setVisibility(isActivate ? View.GONE : View.VISIBLE);
                walletNameTv.setText(currentAccountName
                        + (isActivate ? "" : "(" + getString(R.string.str_inactive) + ")"));
                break;
        }

        if (isPrice && isBalance) {
            if (bdBalance != null && bdPrice != null) {
                bdTotalAmount = bdBalance.multiply(bdPrice);
                String total = bdTotalAmount.stripTrailingZeros().toPlainString();
                walletTotalBalanceTv.setText("$" + total);
            }
        }
    }


    @BusUtils.Bus(tag = BUS_TO_WALLET)
    public void busToWallet(ToWallet toWallet) {
        if (!ObjectUtils.isEmpty(toWallet)) {
            int type = toWallet.getType();
            this.wallet = toWallet.getWallet();
            currentAccountName = wallet.getCurrentAccountName();
            privatekey = wallet.getPrivateKey();
            publicKey = wallet.getPublicKey();
            if (ObjectUtils.isEmpty(publicKey)) {
                publicKey = Ecc.privateToPublic(privatekey);
            }
            updateWalletNameView();
            isCutWallet = true;

            initData();
        }
    }


    @BusUtils.Bus(tag = BUS_DELETE_WALLET)
    public void busDeleteWallet() {
        initData();
    }

    @Override
    public void onStart() {
        super.onStart();
        BusUtils.register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        BusUtils.unregister(this);
    }

    @Override
    public void onMoveTarget(int offset) {

    }

    @Override
    public void onMoveRefreshView(int offset) {

    }

    @Override
    public void onRefresh() {
        wallet = WalletUtils.getCurrentWallet(getActivity());
        presenter.requestDIGICCYPrice(Constants.PRICE_MGP);
        if (!ObjectUtils.isEmpty(wallet)) {
            privatekey = wallet.getPrivateKey();
            currentAccountName = wallet.getCurrentAccountName();
            publicKey = wallet.getPublicKey();
            if (ObjectUtils.isEmpty(publicKey)) {
                publicKey = Ecc.privateToPublic(privatekey);
            }
            presenter.requestKeyAccounts(Params.getKeyAccountsPamars(publicKey));
            presenter.requestAccountInfo(Params.getAccountPamars(currentAccountName));
        }
        updateWalletNameView();
        walletNameTv.setText(currentAccountName);
    }

    private void updateWalletNameView() {
        if (ObjectUtils.isEmpty(wallet)) {
            walletName = getString(R.string.str_mgp_wallet_1);
        } else {
            walletName = ObjectUtils.isEmpty(wallet.getWalletName()) ? StringUtils.getString(R.string.str_mgp_wallet_1) : wallet.getWalletName();
        }
        walletMainNameTv.setText(walletName);
    }
}
